import socket
import sys
import time

def tcp_client(ip, port, message, reconnect_interval=1):
    while True:
        try:
            # 创建一个TCP/IP套接字
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            
            # 连接到服务器
            client_socket.connect((ip, port))
            print(f"Connected to server at {ip}:{port}")
            
            try:
                # 发送消息到服务器
                client_socket.sendall(message.encode('utf-8'))
                print(f"Sent message: {message}")
                
                while True:
                    # 接收数据
                    data = client_socket.recv(1024)
                    if not data:
                        break
                    print(f"{data.decode('utf-8')}", end="")
            
            except Exception as recv_error:
                print(f"Error receiving data: {recv_error}")
            
            finally:
                # 关闭套接字
                client_socket.close()
                print("Connection closed.")
                
            # 可以在这里添加逻辑来决定是否继续重连，比如根据接收到的数据
            # 这里为了简单起见，我们直接等待一段时间然后重试
            time.sleep(reconnect_interval)
            
        except Exception as e:
            print(f"Error connecting to server: {e}")
            time.sleep(reconnect_interval)

if __name__ == "__main__":
    if len(sys.argv) != 4:
        print("Usage: python tcp_client.py <IP> <PORT> <MESSAGE>")
        sys.exit(1)
    
    ip = sys.argv[1]
    port = int(sys.argv[2])
    message = sys.argv[3]
    
    tcp_client(ip, port, message)